import tkinter as tk
from tkinter import filedialog, ttk, messagebox
from app.audio_processor import AudioProcessor


class PlaylistView:
    """歌单视图类，负责歌单UI的创建和管理"""
    
    def __init__(self, parent_frame, playlist_manager):
        """初始化歌单视图"""
        self.parent_frame = parent_frame
        self.playlist_manager = playlist_manager
        self.root = None  # 将在创建时设置
        self.dragged_item = None
        
        # 创建菜单栏
        self.create_menu()
        
        # 创建界面组件
        self.create_widgets()
        
    def create_menu(self):
        # 创建一个框架来放置菜单，使其显示在标签页内部
        self.menu_frame = ttk.Frame(self.parent_frame)
        self.menu_frame.pack(fill=tk.X)
        
        # 创建菜单栏（不设置为root的菜单，而是放置在frame中）
        self.menu_bar = tk.Menu(self.menu_frame)
        
        # 文件菜单
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="新建", command=self.new_playlist)
        self.file_menu.add_command(label="打开", command=self.open_playlist)
        self.file_menu.add_command(label="保存", command=self.save_playlist)
        self.file_menu.add_command(label="另存为", command=self.save_playlist_as)
        
        # 编辑菜单
        self.edit_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.edit_menu.add_command(label="添加文件", command=self.add_files)
        self.edit_menu.add_command(label="添加文件夹", command=self.add_folder)
        self.edit_menu.add_command(label="删除选中", command=self.remove_selected)
        self.edit_menu.add_command(label="清空歌单", command=self.clear_playlist)
        
        # 排序菜单
        self.sort_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.sort_menu.add_command(label="按歌名升序", command=lambda: self.sort_playlist("title", "asc"))
        self.sort_menu.add_command(label="按歌名降序", command=lambda: self.sort_playlist("title", "desc"))
        self.sort_menu.add_command(label="按艺术家升序", command=lambda: self.sort_playlist("artist", "asc"))
        self.sort_menu.add_command(label="按艺术家降序", command=lambda: self.sort_playlist("artist", "desc"))
        self.sort_menu.add_command(label="按时长升序", command=lambda: self.sort_playlist("duration", "asc"))
        self.sort_menu.add_command(label="按时长降序", command=lambda: self.sort_playlist("duration", "desc"))
        
        # 创建菜单项按钮
        self.file_menubutton = ttk.Menubutton(self.menu_frame, text="文件")
        self.file_menubutton.config(menu=self.file_menu)
        self.file_menubutton.pack(side=tk.LEFT, padx=5)
        
        self.edit_menubutton = ttk.Menubutton(self.menu_frame, text="编辑")
        self.edit_menubutton.config(menu=self.edit_menu)
        self.edit_menubutton.pack(side=tk.LEFT, padx=5)
        
        self.sort_menubutton = ttk.Menubutton(self.menu_frame, text="排序")
        self.sort_menubutton.config(menu=self.sort_menu)
        self.sort_menubutton.pack(side=tk.LEFT, padx=5)
    
    def set_root(self, root):
        """设置根窗口引用"""
        self.root = root
    
    def create_widgets(self):
        """创建歌单视图的所有UI组件"""
        # 创建歌曲列表视图
        self.create_song_list()
        
        # 创建按钮区域
        self.create_buttons()
    
    def create_song_list(self):
        """创建歌曲列表视图"""
        # 创建列表视图框架
        list_frame = ttk.LabelFrame(self.parent_frame, text="歌曲列表", padding="5")
        list_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 创建Treeview控件
        columns = ("#0", "filename", "artist", "title", "duration")
        self.song_tree = ttk.Treeview(list_frame, columns=columns, show="headings")
        
        # 设置列宽和标题
        self.song_tree.column("#0", width=30)
        self.song_tree.column("filename", width=300, anchor=tk.W)
        self.song_tree.column("artist", width=150, anchor=tk.W)
        self.song_tree.column("title", width=200, anchor=tk.W)
        self.song_tree.column("duration", width=100, anchor=tk.CENTER)
        
        self.song_tree.heading("filename", text="文件名")
        self.song_tree.heading("artist", text="艺术家")
        self.song_tree.heading("title", text="标题")
        self.song_tree.heading("duration", text="时长")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.song_tree.yview)
        self.song_tree.configure(yscroll=scrollbar.set)
        
        # 放置Treeview和滚动条
        self.song_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 绑定双击事件用于播放歌曲
        self.song_tree.bind("<Double-1>", self.on_double_click)
        
        # 绑定拖放事件用于手动调整顺序
        self.song_tree.bind("<Button-1>", self.on_click)
        self.song_tree.bind("<B1-Motion>", self.on_drag)
        
        # 将song_tree传递给playlist_manager
        self.playlist_manager.set_song_tree(self.song_tree)
        
        # 拖放相关变量
        self.dragged_item = None
    
    def create_buttons(self):
        """创建按钮区域"""
        button_frame = ttk.Frame(self.parent_frame)
        button_frame.pack(fill=tk.X, pady=5)
        
        # 添加文件按钮
        add_file_btn = ttk.Button(button_frame, text="添加文件", command=self.add_files)
        add_file_btn.pack(side=tk.LEFT, padx=5)
        
        # 添加文件夹按钮
        add_folder_btn = ttk.Button(button_frame, text="添加文件夹", command=self.add_folder)
        add_folder_btn.pack(side=tk.LEFT, padx=5)
        
        # 删除按钮
        delete_btn = ttk.Button(button_frame, text="删除选中", command=self.remove_selected)
        delete_btn.pack(side=tk.LEFT, padx=5)
        
        # 清空按钮
        clear_btn = ttk.Button(button_frame, text="清空歌单", command=self.clear_playlist)
        clear_btn.pack(side=tk.LEFT, padx=5)
        
        # 上移按钮
        move_up_btn = ttk.Button(button_frame, text="上移", command=lambda: self.move_song("up"))
        move_up_btn.pack(side=tk.LEFT, padx=5)
        
        # 下移按钮
        move_down_btn = ttk.Button(button_frame, text="下移", command=lambda: self.move_song("down"))
        move_down_btn.pack(side=tk.LEFT, padx=5)
        
        # 搜索框
        search_frame = ttk.Frame(button_frame)
        search_frame.pack(side=tk.RIGHT, padx=5)
        
        ttk.Label(search_frame, text="搜索: ").pack(side=tk.LEFT)
        self.search_entry = ttk.Entry(search_frame, width=20)
        self.search_entry.pack(side=tk.LEFT, padx=5)
        self.search_entry.bind("<Return>", self.on_search)
        
        search_btn = ttk.Button(search_frame, text="查找", command=self.on_search)
        search_btn.pack(side=tk.LEFT)
    
    # 事件处理方法
    def new_playlist(self):
        """创建新的歌单"""
        if self.root:
            self.playlist_manager.new_playlist(self.root)
    
    def open_playlist(self):
        """打开已有歌单"""
        # 检查是否需要保存当前歌单
        if self.playlist_manager.songs and self.root and tk.messagebox.askyesno("保存", "是否保存当前歌单？"):
            if not self.playlist_manager.save_playlist():
                return
        
        # 打开文件对话框
        file_path = filedialog.askopenfilename(
            filetypes=[("M3U播放列表", "*.m3u"), ("所有文件", "*.*")]
        )
        
        if file_path and self.root:
            self.playlist_manager.load_playlist(file_path, self.root)
    
    def save_playlist(self):
        """保存当前歌单"""
        if not self.playlist_manager.current_playlist_path:
            return self.save_playlist_as()
        return self.playlist_manager.save_playlist()
    
    def save_playlist_as(self):
        """将当前歌单另存为新文件"""
        file_path = filedialog.asksaveasfilename(
            defaultextension=".m3u",
            filetypes=[("M3U播放列表", "*.m3u"), ("所有文件", "*.*")]
        )
        
        if file_path and self.root:
            self.playlist_manager.current_playlist_path = file_path
            self.root.title(f"歌单管理器 - {file_path.split('/')[-1]}")
            return self.playlist_manager.save_playlist()
        
        return False
    
    def add_files(self):
        """添加音频文件"""
        file_paths = filedialog.askopenfilenames(
            filetypes=[
                ("音频文件", "*.mp3 *.flac *.wav *.ogg *.wma *.m4a"),
                ("所有文件", "*.*")
            ]
        )
        
        for file_path in file_paths:
            self.playlist_manager.add_song(file_path)
    
    def add_folder(self):
        """添加文件夹中的所有音频文件"""
        folder_path = filedialog.askdirectory()
        
        if folder_path and self.root:
            audio_files = AudioProcessor.scan_directory_for_audio(folder_path)
            added_count = len(audio_files)
            
            for file_path in audio_files:
                self.playlist_manager.add_song(file_path)
            
            if added_count > 0:
                tk.messagebox.showinfo("成功", f"已添加 {added_count} 首歌曲")
            else:
                tk.messagebox.showinfo("提示", "所选文件夹中没有找到音频文件")
    
    def remove_selected(self):
        """删除选中的歌曲"""
        self.playlist_manager.remove_selected()
    
    def clear_playlist(self):
        """清空当前歌单"""
        self.playlist_manager.clear_playlist()
    
    def sort_playlist(self, key, order):
        """排序歌单中的歌曲"""
        self.playlist_manager.sort_playlist(key, order)
    
    def move_song(self, direction):
        """移动选中的歌曲位置"""
        self.playlist_manager.move_song(direction)
    
    def on_search(self, event=None):
        """搜索歌曲"""
        search_text = self.search_entry.get()
        self.playlist_manager.search_song(search_text)
    
    def on_double_click(self, event=None):
        """双击播放歌曲"""
        self.playlist_manager.play_song()
    
    def on_click(self, event=None):
        """鼠标点击事件，记录被点击的项"""
        item = self.song_tree.identify_row(event.y)
        if item:
            self.dragged_item = item
            self.song_tree.selection_set(item)
    
    def on_drag(self, event=None):
        """鼠标拖拽事件，用于调整歌曲顺序"""
        if not self.dragged_item:
            return
        
        # 获取当前鼠标位置对应的项
        target_item = self.song_tree.identify_row(event.y)
        if target_item and target_item != self.dragged_item:
            # 获取两个项的索引
            dragged_index = self.song_tree.index(self.dragged_item)
            target_index = self.song_tree.index(target_item)
            
            # 重新排序歌曲
            new_index = self.playlist_manager.reorder_songs(dragged_index, target_index)
            
            # 更新拖拽项的引用
            self.dragged_item = self.song_tree.get_children()[new_index]